//
//  ReportViewController.m
//  AAIM
//
//  Created by 远的小布丁 on 2019/12/21.
//  Copyright © 2019 AAIM. All rights reserved.
//

#import "ReportViewController.h"
#import "TZImagePickerController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "TZImageManager.h"
#import "ContactRequestLogic.h"
@interface ReportViewController ()<UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIGestureRecognizerDelegate,TZImagePickerControllerDelegate>
{
    UILabel * placeHolderLabel;
    
    
}
@property (nonatomic,strong)UILabel * titleLbl;
@property (nonatomic,strong)UIImageView * addImg;
@property (nonatomic,strong)UITextView * contentTextView;
@property (nonatomic,strong)UILabel * imgCountLbl;
@property (nonatomic,strong)UIButton * submitBtn;
@property (nonatomic,strong)UILabel * countLbl;
@property (nonatomic,strong)UIScrollView * imgBackScrollView;
@property (nonatomic,strong)NSMutableArray * imgAry;
@property (nonatomic,strong)NSMutableArray * selectImgAry;//新选择的图片
@property (nonatomic,copy)UITapGestureRecognizer * tap;
@property (nonatomic,copy)NSString * imgUrlStr;
@property (nonatomic,copy)NSString * contentStr;
@property (nonatomic,copy)NSString * isStart;

@end

@implementation ReportViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.gk_navTitle = @"举报";
    self.gk_navLineHidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    
}

- (void)setUI{
    [self.view addSubview:self.titleLbl];
    [self.view addSubview:self.imgCountLbl];
    [self.view addSubview:self.imgBackScrollView];
    [self.view addSubview:self.contentTextView];
    [self.view addSubview:self.submitBtn];
    [self.view addSubview:self.countLbl];
    
    [_titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(kTopHeight+10);
        make.left.equalTo(self.view.mas_left).offset(15.f);
        make.width.offset(200.f);
    }];
    [_imgCountLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-15.f);
        make.centerY.equalTo(self.titleLbl.mas_centerY);
    }];
    [_imgBackScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLbl.mas_bottom);
        make.left.equalTo(self.view.mas_left).offset(15.f);
        make.right.equalTo(self.view.mas_right).offset(-15.f);
        make.height.offset(100.f);
    }];
    UIView * line = [UIView new];
    line.backgroundColor = KHEXCOLOR(@"#F4F4F4");
    line.height = 1;
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.imgBackScrollView.mas_bottom).offset(8.f);
        make.left.equalTo(self.view.mas_left).offset(15.f);
        make.right.equalTo(self.view.mas_right).offset(-15.f);
    }];
    [_contentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(line.mas_bottom).offset(8.f);
        make.left.equalTo(self.view.mas_left).offset(15.f);
        make.right.equalTo(self.view.mas_right).offset(-15.f);
        make.height.offset(118.f);
    }];
    [_countLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentTextView.mas_bottom).offset(8.f);
        make.right.equalTo(self.view.mas_right).offset(-15.f);
    }];
    [_submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentTextView.mas_bottom).offset(68.f);
        make.left.equalTo(self.view.mas_left).offset(15.f);
        make.right.equalTo(self.view.mas_right).offset(-15.f);
        make.height.offset(45.f);
    }];
    _tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(choosePictrueWay:)];
    _tap.numberOfTapsRequired = 1;
    _tap.numberOfTouchesRequired = 1;
    
    for (int i= 0; i<3; i++) {
        UIImageView * img = [[UIImageView alloc]init];
        
        img.frame = CGRectMake((70+15)*i, 15, 70, 70);
        img.tag = 10+i;
        if (i==0) {
            img.image = [UIImage imageNamed:@"加"];
            img.userInteractionEnabled = YES;
            [img addGestureRecognizer:_tap];
        }
        
        [self.imgBackScrollView addSubview:img];
        UIButton * deleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [deleBtn setImage:[UIImage imageNamed:@"移除"] forState:UIControlStateNormal];
        [deleBtn addTarget:self action:@selector(deleteImg:) forControlEvents:UIControlEventTouchUpInside];
        [_imgBackScrollView addSubview:deleBtn];
        deleBtn.hidden = YES;
        deleBtn.tag = 20+i;
        
        [deleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(img.mas_top).offset(-10);
            make.right.equalTo(img.mas_right).offset(10);
            make.size.mas_equalTo(CGSizeMake(18, 18));
        }];
    }
    
    
    
}

- (void)deleteImg:(UIButton *)sender{
    NSInteger t = sender.tag -20;
    [_selectImgAry removeObjectAtIndex:t];
    [_imgAry removeObjectAtIndex:t];
    if (self.selectImgAry.count <3) {
        for (int i= 0; i<self.selectImgAry.count +1; i++) {
            UIImageView * img = [self.view viewWithTag:10+i];
            UIButton * btn = [self.view viewWithTag:20+i];
            if (i==self.selectImgAry.count) {
                img.image = [UIImage imageNamed:@"加"];
                img.userInteractionEnabled = YES;
                [img addGestureRecognizer:self.tap];
                btn.hidden = YES;
            }else{
                img.image = self.selectImgAry[i];
                btn.hidden = NO;
            }
            
        }
        if (self.selectImgAry.count == 1) {
           UIImageView * img = [self.view viewWithTag:12];
            img.hidden = YES;
        }
        if (self.selectImgAry.count == 0) {
           UIImageView * img = [self.view viewWithTag:11];
            img.hidden = YES;
        }
        _imgCountLbl.text = [NSString stringWithFormat:@"%ld张",_selectImgAry.count];
        
    }else if (self.selectImgAry.count>=3){
        for (int i= 0; i<3; i++) {
            UIImageView * img = [self.view viewWithTag:10+i];
            UIButton * btn = [self.view viewWithTag:20+i];
            btn.hidden = NO;
            img.image = self.selectImgAry[i];
            
        }
        
    }
}


- (void)choosePictrueWay:(UITapGestureRecognizer *)tap{
    UIAlertController * alerController = [UIAlertController alertControllerWithTitle:@"" message:@"选择图片" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertAction * camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera];
    }];
    
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openPhotoLibrary];
    }];
    
    [alerController addAction:camera];
    [alerController addAction:photo];
    [alerController addAction:cancle];
    
    [self presentViewController:alerController animated:YES completion:nil];
}

/*** 调用照相机 */
- (void)openCamera{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES; //可编辑
    //判断是否可以打开照相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        NSLog(@"没有摄像头");
        [self showTipHudWithText:@"打开相机失败"];
    }
}
/*** 打开相册  */
-(void)openPhotoLibrary{
    // 进入相册
    
    TZImagePickerController * imagePickVC = [[TZImagePickerController alloc]initWithMaxImagesCount:3 delegate:self];
    imagePickVC.allowPickingVideo = NO;
    imagePickVC.selectedAssets = _imgAry;
    [imagePickVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        KWeakSelf;
        [weakSelf.selectImgAry removeAllObjects];
        [weakSelf.imgAry removeAllObjects];
        [weakSelf.imgAry addObjectsFromArray:assets];
        [weakSelf.selectImgAry addObjectsFromArray:photos];
        weakSelf.imgCountLbl.text = [NSString stringWithFormat:@"%ld张",weakSelf.selectImgAry.count];
        if (weakSelf.selectImgAry.count <3) {
            for (int i= 0; i<weakSelf.selectImgAry.count +1; i++) {
                UIImageView * img = [self.view viewWithTag:10+i];
                UIButton * btn = [self.view viewWithTag:20+i];
                if (i==weakSelf.selectImgAry.count) {
                    img.image = [UIImage imageNamed:@"加"];
                    img.userInteractionEnabled = YES;
                    [img addGestureRecognizer:weakSelf.tap];
                    btn.hidden = YES;
                }else{
                    img.image = weakSelf.selectImgAry[i];
                    btn.hidden = NO;
                }
                
            }
            
            
        }else if (weakSelf.selectImgAry.count>=3){
            for (int i= 0; i<3; i++) {
                UIImageView * img = [self.view viewWithTag:10+i];
                UIButton * btn = [self.view viewWithTag:20+i];
                btn.hidden = NO;
                img.image = weakSelf.selectImgAry[i];
                
            }
            
        }
        
    }];
    [self presentViewController:imagePickVC animated:YES completion:nil];
    
}

#pragma mark - UIImagePickerControllerDelegate

// 拍照完成回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info{
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    //    NSLog(@"finish..");
    KWeakSelf;
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera){
        //图片存入相册
        //        _userHeaderImageView.image = image;
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        
        //        [picker dismissViewControllerAnimated:YES completion:nil];
        NSString * type = [info objectForKey:UIImagePickerControllerMediaType];
        if ([type isEqualToString:@"public.image"]) {
            TZImagePickerController * pickVC = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
            [pickVC showProgressHUD];
            
            [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES needFetchAssets:YES completion:^(TZAlbumModel *model) {
                [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                    [pickVC hideProgressHUD];
                    TZAssetModel * assetModel = [models firstObject];
                    if (pickVC.sortAscendingByModificationDate) {
                        assetModel = [models lastObject];
                    }
                    [weakSelf.selectImgAry addObject:image];
                    [weakSelf.imgAry addObject:assetModel.asset];
                    KWeakSelf;
                    weakSelf.imgCountLbl.text = [NSString stringWithFormat:@"%lu张",(unsigned long)weakSelf.selectImgAry.count];
                    if (weakSelf.selectImgAry.count <3) {
                        for (int i= 0; i<weakSelf.selectImgAry.count +1; i++) {
                            UIImageView * img = [self.view viewWithTag:10+i];
                            UIButton * btn = [self.view viewWithTag:20+i];
                            if (i==weakSelf.selectImgAry.count) {
                                img.image = [UIImage imageNamed:@"加"];
                                img.userInteractionEnabled = YES;
                                [img addGestureRecognizer:weakSelf.tap];
                                btn.hidden = YES;
                            }else{
                                img.image = weakSelf.selectImgAry[i];
                                btn.hidden = NO;
                            }
                            
                        }
                        
                    }else if (weakSelf.selectImgAry.count>=3){
                        for (int i= 0; i<3; i++) {
                            UIImageView * img = [self.view viewWithTag:10+i];
                            UIButton * btn = [self.view viewWithTag:20+i];
                            img.image = weakSelf.selectImgAry[i];
                            btn.hidden = NO;
                        }
                    }
                }];
            }];
        }
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

//进入拍摄页面点击取消按钮
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}


//提交
- (void)submitBtnActive:(UIButton *)sender{
    if (_selectImgAry.count <=0) {
        [self showTipHudWithText:@"请上传图片"];
        return;
    }
    if ([CommonTools isEmpty:_contentTextView.text]) {
        [self showTipHudWithText:@"请填写内容"];
        return;
    }
    _imgUrlStr = nil;
    [self showAlwaysTipHudWithText:@"上传资料中，请稍等"];

    KWeakSelf;
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
        sleep(1);
        for (int i = 0; i<weakSelf.selectImgAry.count; i++) {
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
            [LoginRequestLogic upLoadReportPictureFile:weakSelf.selectImgAry[i] withToken:[LoginManager shareLoginManager].userModel.token withType:@"pic" Success:^(NSDictionary * _Nonnull Dict) {

                NSLog(@"---111-%@",Dict);
                KWeakSelf;
                if ([Dict[@"code"] integerValue] == 200) {
                    if ([CommonTools isEmpty:weakSelf.imgUrlStr]) {
                        weakSelf.imgUrlStr = [NSString stringWithFormat:@"%@",Dict[@"data"]];
                    }else{
                        weakSelf.imgUrlStr = [NSString stringWithFormat:@"%@,%@",weakSelf.imgUrlStr,Dict[@"data"]];
                    }
                }
                NSLog(@"任务1-执行第%d次",i);
                dispatch_semaphore_signal(semaphore);
            } failure:^(NSString * _Nonnull errMsg) {
                [self hideHud];
                dispatch_semaphore_signal(semaphore);
                NSLog(@"出错了：%@",errMsg);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }
    });

    dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"任务2开始执行");
            [weakSelf upLoadReport];
        });
    });
    
}

- (void)upLoadReport{
        if ([_reportType isEqualToString:@"friend"]) {
            [ContactRequestLogic reportUserOrGroupWithContent:self.contentStr withFuuid:self.fuuid withImgUrl:self.imgUrlStr groupid:@"" Success:^(NSDictionary * _Nonnull Dict) {
                //                     NSLog(@"举报结果：%@",Dict[@"message"]);
                //                     NSLog(@"举报信息：%@",Dict);
                [self hideHud];
                [self showTipHudWithText:Dict[@"message"]];
            } failure:^(NSString * _Nonnull errMsg) {
                [self hideHud];
                [self showTipHudWithText:errMsg];
                
            }];
        }else{
            [ContactRequestLogic reportUserOrGroupWithContent:self.contentStr withFuuid:@"" withImgUrl:self.imgUrlStr groupid:self.fuuid Success:^(NSDictionary * _Nonnull Dict) {
                //                     NSLog(@"举报结果：%@",Dict[@"message"]);
                //                     NSLog(@"举报信息：%@",Dict);
                [self hideHud];
                [self showTipHudWithText:Dict[@"message"]];
            } failure:^(NSString * _Nonnull errMsg) {
                [self hideHud];
                [self showTipHudWithText:errMsg];
                
            }];
        }
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    NSLog(@"1--%@",textView.text);
}

-(void)textViewDidChange:(UITextView *)textView{
    NSLog(@"2--%@",textView.text);
    _contentStr = textView.text;
}

-(void)textViewDidChangeSelection:(UITextView *)textView{
    NSLog(@"3--%@",textView.text);
    _contentStr = textView.text;
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{    if (![text isEqualToString:@""]){
    
    placeHolderLabel.hidden = YES;
}
    
    if ([text isEqualToString:@""] && range.location == 0 && range.length == 1)
        
    {
        
        placeHolderLabel.hidden = NO;
        
    }
    
    
    if (range.length + range.location > textView.text.length) {
        
        return NO;
        
    }
    NSLog(@"%@",textView.text);
    NSUInteger length = textView.text.length + text.length - range.length;
    if (length>=200) {
        _countLbl.text = @"200/200";
    }else{
         _countLbl.text = [NSString stringWithFormat:@"%ld/200",length];
    }
   
    
    return length <= 200;
    
    
}

-(UILabel *)titleLbl{
    if (!_titleLbl) {
        _titleLbl = [[UILabel alloc]init];
        _titleLbl.text = @"图片证据（必填）";
        _titleLbl.font = kMainFont(14.f);
        _titleLbl.textColor = KHEXCOLOR(@"#262B2F");
    }
    return _titleLbl;
}
-(UILabel *)imgCountLbl{
    if (!_imgCountLbl) {
        _imgCountLbl = [[UILabel alloc]init];
        _imgCountLbl.text = @"0张";
        _imgCountLbl.font = kMainFont(14.f);
        _imgCountLbl.textColor = KHEXCOLOR(@"#AFAFAF");
    }
    return _imgCountLbl;
}

-(UILabel *)countLbl{
    if (!_countLbl) {
        _countLbl = [[UILabel alloc]init];
        _countLbl.text = @"0/200";
        _countLbl.font = kMainFont(12.f);
        _countLbl.textColor = KHEXCOLOR(@"#AFAFAF");
    }
    return _countLbl;
}

//- (UIImageView *)addImg{
//    if (!_addImg) {
//        _addImg = [[UIImageView alloc]init];
//        _addImg.image = [UIImage imageNamed:@"加"];
//
//    }
//    return _addImg;
//}

-(UITextView *)contentTextView{
    if (!_contentTextView) {
        _contentTextView = [[UITextView alloc]init];
        _contentTextView.backgroundColor = KHEXCOLOR(@"#F5F5F5");
        _contentTextView.textColor = [UIColor blackColor];
        _contentTextView.font = kMainFont(12);
        _contentTextView.layer.cornerRadius = 4;
        _contentTextView.layer.masksToBounds = YES;
        _contentTextView.delegate = self;
        //允许编辑
        _contentTextView.editable = YES;
        //用户交互     ///////若想有滚动条 不能交互 上为No，下为Yes
        _contentTextView.userInteractionEnabled = YES; ///
        placeHolderLabel = [[UILabel alloc] init];
        placeHolderLabel.text = @"投诉内容（必填）";
        placeHolderLabel.numberOfLines = 0;
        placeHolderLabel.textColor = [UIColor lightGrayColor];
        [placeHolderLabel sizeToFit];
        [_contentTextView addSubview:placeHolderLabel];
        
        placeHolderLabel.font = [UIFont systemFontOfSize:12.f];
        
        [_contentTextView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
    }
    return _contentTextView;
}

- (UIScrollView *)imgBackScrollView{
    
    if (!_imgBackScrollView) {
        _imgBackScrollView = [[UIScrollView alloc]init];
        _imgBackScrollView.contentSize = CGSizeMake(69.f, 70.f);
        _imgBackScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    }
    return _imgBackScrollView;
}

- (UIButton *)submitBtn{
    if (!_submitBtn) {
        _submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_submitBtn setBackgroundColor:KHEXCOLOR(@"#F5F5F5")];
        [_submitBtn setTitle:@"举报" forState:UIControlStateNormal];
        [_submitBtn setTitleColor:KHEXCOLOR(@"#262B2F") forState:UIControlStateNormal];
        [_submitBtn addTarget:self action:@selector(submitBtnActive:) forControlEvents:UIControlEventTouchUpInside];
        _submitBtn.titleLabel.font = kMainFont(15.f);
    }
    return _submitBtn;
    
}

-(NSMutableArray *)imgAry{
    if (!_imgAry) {
        _imgAry = [NSMutableArray array];
    }
    return _imgAry;
}
-(NSMutableArray *)selectImgAry{
    if (!_selectImgAry) {
        _selectImgAry = [NSMutableArray array];
    }
    return _selectImgAry;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
